package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.UserDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SendSms;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private CacheManager cacheManager;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/sendMsg")
    public R<String>sendMsg(@RequestBody User user, HttpSession session) throws Exception {
        String phone = user.getPhone();
        String code = Integer.toString(ValidateCodeUtils.generateValidateCode(4));
        System.out.println("code = " + code);
        session.setAttribute(phone, code);
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
        return R.success(code);
    }
    @PostMapping("/login")
   public R<String>login(@RequestBody UserDto userDto,HttpSession session){
        //String code1= (String) session.getAttribute(userDto.getPhone());
        String code1 = (String) redisTemplate.opsForValue().get(userDto.getPhone());
        String code2=userDto.getCode();
        if (!code1.equals(code2)){
            return R.error("登录失败");
        }
       QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",userDto.getPhone());
       User one = userService.getOne(queryWrapper);
       if (one == null){
           userDto.setName("黑马菜只因");
           userDto.setStatus(1);
           userService.save(userDto);
       }else {
           userDto.setId(one.getId());
       }

       session.setAttribute("user",userDto);
        //登录成功从redis删除验证码
        redisTemplate.delete(one.getPhone());
       return R.success("登录成功");
   }


}